package messagepasser;

/**
 * 
 * @author Rishit Shroff(rshroff)
 * @author Huimin Yang(huiminy)
 * @description Contains the Vector class 
 */

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Vector extends ClockService implements Serializable, Cloneable{
	
	private List<Integer> clock = new ArrayList<Integer>();
	private int mySlot;
	
	
	public List<Integer> getClock() {
		return clock;
	}

	public void setClock(List<Integer> clock) {
		this.clock = clock;
	}

	

	public Vector() {
		super();
		clockType = "Vector";
		mySlot = 0;
	}
	
	public void initialize(List<String> nodeNames, String myName) {
		for(int i = 0; i < nodeNames.size(); i++) {
			clock.add(0);
		}
		for(int i = 0; i < nodeNames.size(); i++) {
			if(nodeNames.get(i).equals(myName)) {
				mySlot = i;
			}
		}
	}
	
	public void doService() {
		int oldValue = clock.get(mySlot);
		clock.set(mySlot, oldValue + 1);
	}
	
	public int getMySlot() {
		return mySlot;
	}
	
	public int getSlotTime(int slot) {
		return clock.get(slot);
	}
	
	public void syncClock(List<String> nodeNames, ClockService senderClock) {
		for (int i = 0; i < nodeNames.size(); i++) {
			int myTime = clock.get(i);
			int senderTime = ((Vector)senderClock).getSlotTime(i);
			if (myTime < senderTime) {
				clock.set(i, senderTime);
			}
		}
	}
	
	public String toString() {
	    return clock.toString(); 
	}
	
	public boolean equals(Object obj) {
		  if (obj instanceof Vector)
		  {
			
		    Vector rhs = (Vector) obj;
		    for (int index = 0; index < this.clock.size(); index++) {
		    	if(this.clock.get(index).intValue() != rhs.getClock().get(index).intValue()) {
		    		return false;
		    	}
		    }
		  }
		  return true;
	}
	
	public Object clone(){
        // The cast in the line below throws an exception!
        //
        Vector newObject = new Vector();  

        // You _never_ get here because the line above throws
        // an exception.
        newObject.clock = new ArrayList<Integer>();
        newObject.mySlot = this.mySlot;
        for (Integer i : this.clock) {
        	newObject.clock.add(new Integer (i.intValue()));
        }
    
        return newObject;
    }
	
	public String getTime() {
		return this.clock.toString();
	} 
	
}
